package com.mike.uaa.server.controllers;

import com.mike.uaa.core.Authentication;
import com.mike.uaa.context.SecurityContextHolder;
import com.mike.uaa.server.domain.response.AuthenticationResponse;
import com.mike.uaa.server.service.AuthenticationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author z zhang
 */
@RestController
@RequiredArgsConstructor
public class AuthenticationController {

    private final AuthenticationService authenticationService;

    @GetMapping("/hello")
    @ResponseBody
    public Authentication hello() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    // 显示登录页面
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }


    @PostMapping("/login")
    public AuthenticationResponse login(HttpServletRequest request, HttpSession session, Model model) {
        String parameter = request.getParameter("grant_type");
        String parameter1 = request.getParameter("password");

        String parameter2 = request.getParameter("username");
        AuthenticationResponse response = authenticationService.login(request);
      return response;
    }

//    @PostMapping("/login")
//    public String login(@RequestParam(value = "redirect", required = false) String redirect,HttpServletRequest request, HttpSession session, Model model) {
//
//        AuthenticationResponse response = authenticationService.login(request);
//        if (response.isAuthenticated()) {
//            session.setAttribute("username", response.getUsername());
//            session.setAttribute("tokenValue", response.getTokenValue());
//            return "/home";
//        } else {
//            model.addAttribute("error", "用户名或密码错误");
//            return "login"; // 返回登录页并显示错误
//        }
//    }
}
